package com.swak.persistence;

import java.util.List;

import com.swak.entity.IdEntity;
import com.swak.utils.Lists;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

/**
 * DTO 的分类
 * 
 * @author 618lf
 */
@Getter
@Setter
@Accessors
@SuppressWarnings({ "rawtypes" })
public class Classify<PO extends IdEntity> {
	private List<PO> inserts = Lists.newArrayList();
	private List<PO> updates = Lists.newArrayList();
	private List<PO> detetes = Lists.newArrayList();

	/**
	 * 创建分类：分出新增、更新、删除
	 * 
	 * @param dtos
	 * @param pos
	 * @return
	 */
	public static <PO extends IdEntity> Classify<PO> of(List<PO> dtos, List<PO> pos) {
		Classify<PO> classify = new Classify<>();
		if (dtos == null || dtos.size() == 0) {
			classify.setDetetes(pos);
			return classify;
		}
		for (PO dto : dtos) {
			if (dto.getId() == null) {
				classify.getInserts().add(dto);
				continue;
			}
			if (!(pos == null || pos.size() == 0)) {
				PO found = null;
				for (PO po : pos) {
					if (dto.getId().equals(po.getId())) {
						found = po;
						break;
					}
				}
				if (found != null) {
					classify.getUpdates().add(dto);
				}
			} else if (dto.getId() != null) {
				classify.getUpdates().add(dto);
			}
		}
		if (!(pos == null || pos.size() == 0)) {
			for (PO po : pos) {
				boolean found = false;
				for (PO dto : dtos) {
					if (po.getId().equals(dto.getId())) {
						found = true;
						break;
					}
				}
				if (!found) {
					classify.getDetetes().add(po);
				}
			}
		}
		return classify;
	}
}
